import jwt from 'jsonwebtoken'

export class TokenDataBase {
  // 签发时间
  iat?: number
  // 过期时间
  exp?: number
}

export type TokenData<T = Record<string, any>> = TokenDataBase & T

// 默认配置
const TOKEN_EXP = 1000 * 60 * 60 * 24 * 366

const TOKEN_SECRET = 'TOKEN_SECRET'

// 创建 token
export const createToken = async<T = Record<string, any>>(data: TokenData<T>, _secret = TOKEN_SECRET, _exp = TOKEN_EXP): Promise<string> => {
  const iat = Date.now()
  const exp = iat + _exp

  const payload = Object.assign({}, data, {
    // 签发时间
    iat,
    // 过期时间
    exp
  })

  const token = jwt.sign(JSON.stringify(payload), _secret)

  return token
}

// 解析 token
export const parseToken = <T = Record<string, any>>(token: string, _secret = TOKEN_SECRET) => new Promise((resolve: (tokenData: TokenData<T>) => void, reject) => {
  if (!token || !token.trim()) {
    reject('token 不能为空')
  }

  jwt.verify(token, _secret, (err, payload) => {
    if (err) {
      reject(err)
    } else {
      // const tokenData = payload as TokenData
      // const now = new Date()

      // if (now.getTime() < tokenData.exp) {
      //   resolve(tokenData)
      // } else {
      //   reject('token 已过期')
      // }
      resolve(payload as TokenData<T>)
    }
  })
})
